package com.express.e.root.wx.controller;

import com.express.e.root.annotation.ResponseBody;
import com.express.e.root.annotation.ResponseView;
import com.express.e.root.bean.Admin;
import com.express.e.root.bean.Delivery;
import com.express.e.root.bean.Message;
import com.express.e.root.enums.DeliveryEnum;
import com.express.e.root.service.AdminService;
import com.express.e.root.service.DeliveryService;
import com.express.e.root.service.impl.AdminServiceImpl;
import com.express.e.root.service.impl.DeliveryServiceImpl;
import com.express.e.root.utils.AdminWrap;
import com.express.e.root.utils.DeliveryWrap;
import com.express.e.root.utils.FomatDateUtil;
import com.express.e.root.utils.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class CourierController {
    private AdminService adminService = new AdminServiceImpl();
    private DeliveryService deliveryService = new DeliveryServiceImpl();

    /**
     * 若数据库无此用户名，则注册，否则拒绝
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/couriers/couriersRegister.do")
    public String couriersRegister(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        String pwd = request.getParameter("pwd");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String cardId = request.getParameter("cardId");
        Admin admin = new Admin(
                name,
                pwd,
                "127.0.0.1",
                new Date(System.currentTimeMillis()),
                0,
                1,
                phone,
                cardId
        );
        Admin queryByName = adminService.queryByName(name);
        if (null == queryByName || queryByName.getAdminId() == null) {
            Admin addAdmin = adminService.addAdmin(admin);
            ArrayList<Object> objects = new ArrayList<>();
            if (addAdmin.getAdminId() != null) {
                AdminWrap adminWrap = new AdminWrap(
                        addAdmin.getAdminId(),
                        addAdmin.getAdminName(),
                        addAdmin.getAdminPwd(),
                        addAdmin.getLoginIP(),
                        FomatDateUtil.formatDate(addAdmin.getLastTime()),
                        addAdmin.getState()==0?"离线":"上线",
                        addAdmin.getRole()==0?"超级管理员":"快递员",
                        addAdmin.getPhone(),
                        addAdmin.getCardId()
                );
                objects.add(adminWrap);
                String toJson = JSONUtil.toJson(new Message(200, "快递员注册成功", objects));
                System.out.println(toJson);
                return toJson;
            }
            String toJson = JSONUtil.toJson(new Message(400, "快递员添加失败", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "快递员注册失败，快递员名已存在", null));
        System.out.println(toJson);
        return toJson;
    }

    @ResponseBody("/wx/couriers/login.do")
    public String loginIn(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        String phone = req.getParameter("phone");
        String identifyCode = req.getParameter("identifyCode");

        /**
         * 此处插入验证码确认代码，错误则返回，正确继续
         */
        Integer s = (Integer) req.getSession().getAttribute("code");
        System.out.println(s);
        System.out.println(Integer.valueOf(identifyCode));
        if (!(s.equals(Integer.valueOf(identifyCode)))){
            Message msg = new Message(400, "快递员登陆失败，验证码不正确", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }

        Admin admin4login = adminService.queryByPhone(phone);
        Admin admin = adminService.loginIn(admin4login);
        if (null!=admin&&null != admin.getAdminName()) {
            req.getSession().setAttribute("adminName",admin4login.getAdminName());
            req.getSession().setAttribute("adminPwd",admin4login.getAdminPwd());
            List objects = new ArrayList<>();
            objects.add(admin);
            Message msg = new Message(200, "快递员登陆成功", objects);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            req.getSession().removeAttribute("username");
            req.getSession().removeAttribute("pwd");
            req.getSession().removeAttribute("usersname");
            req.getSession().removeAttribute("userspwd");
            return toJson;
        }

        Message msg = new Message(400, "快递员登陆失败，检查用户名与密码是否匹配", null);
        String toJson = JSONUtil.toJson(msg);
        System.out.println(toJson);
        return toJson;
    }

    @ResponseBody(value = "/wx/couriers/loginOut.do")
    public String loginOut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String adminName = (String) req.getSession().getAttribute("adminName");
        String adminPwd = (String) req.getSession().getAttribute("adminPwd");

        System.out.println(adminName);
        System.out.println(adminPwd);


        Admin admin4loginOut = adminService.queryByName(adminName);
        if (!adminService.loginOut(admin4loginOut)) {
            Message msg = new Message(400, "快递员退出失败", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        } else {
            req.getSession().removeAttribute("adminName");
            req.getSession().removeAttribute("adminPwd");
            req.getSession().setMaxInactiveInterval(1);
            Message msg = new Message(200, "快递员退出成功", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
    }

    /**
     * 根据快递单号查询快递
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody("/wx/couriers/findByNum.do")
    public String findByNum(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        String number = req.getParameter("number");
        System.out.println(number);
        if (null==number || number.isEmpty()) {
            return JSONUtil.toJson(new Message(401, "快递单号为空！", null));
        }

        Delivery delivery = deliveryService.queryByNum(number);

        if (delivery != null && delivery.getDeliveryAcceptor() != null) {
            DeliveryWrap deliveryWrap = new DeliveryWrap(
                    delivery.getDeliveryId(),
                    delivery.getDeliveryCode(),
                    delivery.getDeliveryCompany(),
                    delivery.getDeliveryAcceptor(),
                    delivery.getAcceptorPhone(),
                    delivery.getDeliveryNum(),
                    delivery.getDeliveryState()==1?"已取件":"未取件",
                    FomatDateUtil.formatDate(delivery.getStateChangeTime())
            );

            ArrayList<Object> objects = new ArrayList<>();
            objects.add(deliveryWrap);
            String toJson = JSONUtil.toJson(new Message(200, "根据快递单号成功找到此快递", objects));
            System.out.println(toJson);
            return toJson;
        }
        return JSONUtil.toJson(new Message(400, "根据快递单号未找到此快递", null));
    }

    @ResponseBody("/wx/couriers/findByCode.do")
    public String findByCode(HttpServletRequest req, HttpServletResponse resp){
        resp.setCharacterEncoding("utf-8");
        String code = req.getParameter("code");
        Delivery delivery = deliveryService.queryByCode(Integer.valueOf(code));
        if (delivery != null && null !=delivery.getDeliveryId()) {
            DeliveryWrap deliveryWrap = new DeliveryWrap(
                    delivery.getDeliveryId(),
                    delivery.getDeliveryCode(),
                    delivery.getDeliveryCompany(),
                    delivery.getDeliveryAcceptor(),
                    delivery.getAcceptorPhone(),
                    delivery.getDeliveryNum(),
                    delivery.getDeliveryState()==0?"未取件":"已取件",
                    FomatDateUtil.formatDate(delivery.getStateChangeTime())
            );
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(deliveryWrap);
            String toJson = JSONUtil.toJson(new Message(200, "查找成功！", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "查找失败！", null));
        System.out.println(toJson);
        return toJson;
    }

    /**
     * 取件码取件
     * @param req
     * @param resp
     * @return
     */
    @ResponseBody("/wx/courier/fetchByCode.do")
    public String fetchByCode(HttpServletRequest req, HttpServletResponse resp) {
        resp.setCharacterEncoding("utf-8");
        String code = req.getParameter("code");
        System.out.println(code);
        if (code.isEmpty()) {
            return JSONUtil.toJson(new Message(401, "取件号码为空！", null));
        }

        Delivery delivery = deliveryService.queryByCode(Integer.valueOf(code));

        if (delivery != null && delivery.getDeliveryAcceptor() != null) {
            if (delivery.getDeliveryState() == 1) {
                System.out.println(JSONUtil.toJson(new Message(401, "此快递已取出！", null)));
                return JSONUtil.toJson(new Message(401, "此快递已取出！", null));
            }
            DeliveryWrap deliveryWrap = new DeliveryWrap(
                    delivery.getDeliveryId(),
                    delivery.getDeliveryCode(),
                    delivery.getDeliveryCompany(),
                    delivery.getDeliveryAcceptor(),
                    delivery.getAcceptorPhone(),
                    delivery.getDeliveryNum(),
                    delivery.getDeliveryState()==1?"已取件":"未取件",
                    FomatDateUtil.formatDate(delivery.getStateChangeTime())
            );
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(deliveryWrap);
            if (deliveryService.fetchDelivery(deliveryWrap.getDeliveryNum())) {
                String toJson = JSONUtil.toJson(new Message(200, "根据取件码成功取出此快递", objects));
                System.out.println(toJson);
                return toJson;
            }
            String toJson = JSONUtil.toJson(new Message(400, "根据取件码成功找到此快递，但未能成功取出", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "根据取件码未找到此快递", null));
        System.out.println(toJson);
        return toJson;
    }


    /**
     * 快递员录入快递
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/courier/addDelivery.do")
    public String addDelivery(HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("utf-8");
        String deliveryCode = request.getParameter("number");
        String deliveryCompany = request.getParameter("company");
        String deliveryAcceptor = request.getParameter("userName");
        String acceptorPhone = request.getParameter("userPhone");
        Calendar calendar = Calendar.getInstance();
        Delivery delivery = deliveryService.addDelivery(new Delivery(deliveryCompany, deliveryAcceptor, acceptorPhone, deliveryCode, 0,
                new Date(System.currentTimeMillis())));
        if (delivery == null || delivery.getDeliveryId() == 0) {
            return JSONUtil.toJson(new Message(400, "快递员增加快递失败", null));
        }
        DeliveryWrap deliveryWrap = new DeliveryWrap(
                delivery.getDeliveryId(),
                delivery.getDeliveryCode(),
                delivery.getDeliveryCompany(),
                delivery.getDeliveryAcceptor(),
                delivery.getAcceptorPhone(),
                delivery.getDeliveryNum(),
                delivery.getDeliveryState() == 0 ? DeliveryEnum.STORE.desc : DeliveryEnum.FETCH.desc,
                FomatDateUtil.formatDate(delivery.getStateChangeTime()));
        Map objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("courierName",request.getSession().getAttribute("adminName"));
        objectObjectHashMap.put("dataList",deliveryWrap);
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(objectObjectHashMap);
        String insert = JSONUtil.toJson(new Message(200, "快递员增加快递成功", objects));
        System.out.println(insert);
        return insert;
    }

    @ResponseBody("/wx/courier/queryDeliveryRecords.do")
    public String queryDeliveryRecords(HttpServletRequest request, HttpServletResponse response){
        Object adminname = request.getSession().getAttribute("adminName");
        if (Optional.ofNullable(adminname).isPresent()) {
            String adminName = (String) adminname;
            List<Delivery> queryListByCourier = deliveryService.queryListByCourier(adminName);
            ArrayList<DeliveryWrap> queryByCourierNew = new ArrayList<>();
            for (Delivery d :
                    queryListByCourier) {
                queryByCourierNew.add(new DeliveryWrap(
                        d.getDeliveryId(),
                        d.getDeliveryCode(),
                        d.getDeliveryCompany(),
                        d.getDeliveryAcceptor(),
                        d.getAcceptorPhone(),
                        d.getDeliveryNum(),
                        d.getDeliveryState()==0?"未取件":"已取件",
                        FomatDateUtil.formatDate(d.getStateChangeTime()),
                        d.getInsertCourier()
                ));
            }
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(queryByCourierNew);
            String toJson = JSONUtil.toJson(new Message(200, "查询到快递员历史", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, " 未查询到快递员历史", null));
        System.out.println(toJson);
        return toJson;
    }

    @ResponseBody("/wx/couriers/courierPatchHistory.do")
    public String courierPatchHistory(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        String courierName = (String) request.getSession().getAttribute("adminName");
        System.out.println("快递员名字："+courierName);

        List<Delivery> queryListByName = deliveryService.queryListByCourier(courierName);
        List<DeliveryWrap> queryListWrapper = new ArrayList<>();
        if (queryListByName != null &&  queryListByName.size()>0 ) {
            for (Delivery d :
                    queryListByName) {
                DeliveryWrap deliveryWrap = new DeliveryWrap(
                        d.getDeliveryId(),
                        d.getDeliveryCode(),
                        d.getDeliveryCompany(),
                        d.getDeliveryAcceptor(),
                        d.getAcceptorPhone(),
                        d.getDeliveryNum(),
                        d.getDeliveryState()==0?"未取件":"已取件",
                        FomatDateUtil.formatDate( d.getStateChangeTime())
                );
                queryListWrapper.add(deliveryWrap);
            }
            Object[] deliveryStreamStore = queryListWrapper.stream().filter(delivery -> delivery.getDeliveryState().equals("未取件")).toArray();
            Object[] deliveryStreamFetch = queryListWrapper.stream().filter(delivery -> delivery.getDeliveryState().equals("已取件")).toArray();
            Map<String, Object[]> hashMap = new HashMap<>();
            hashMap.put("store",  deliveryStreamStore);
            hashMap.put("fetch", deliveryStreamFetch);
            ArrayList arrayList = new ArrayList();
            arrayList.add(hashMap);
            Message msg = new Message(200, "查询到该快递员名下派发的所有快递",arrayList);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        Message msg = new Message(400, "未查询到该快递员名下派发的快递", queryListByName);
        String toJson = JSONUtil.toJson(msg);
        System.out.println(toJson);
        return toJson;
    }


    /**
     * 快递员修改密码
     * @param request
     * @param response
     * @return
     */
    @ResponseBody("/wx/couriers/updateInfo.do")
    public String updateInfoCourier(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");

        String code = request.getParameter("code");
        Integer code1 = (Integer) request.getSession().getAttribute("code");
        System.out.println(code);
        System.out.println(request.getSession().getAttribute("code"));
        System.out.println(!(String.valueOf(code).equals(String.valueOf(code1))));
        if (code == null || code1 == null
                || !(String.valueOf(code).equals(String.valueOf(code1)))) {
            Message msg = new Message(400, "快递员验证码失败", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }


        Admin queryByName = adminService.queryByName((String) request.getSession().getAttribute("adminName"));


        if (queryByName == null||queryByName.getAdminId()==null) {
            String toJson = JSONUtil.toJson(new Message(400, "未查询到该快递员信息", null));
            System.out.println(toJson);
            return toJson;
        }
        String courierName = request.getParameter("name");
        String courierPhone = request.getParameter("phone");
        String password = request.getParameter("password");
        System.out.println(courierName);
        System.out.println(courierPhone);
        System.out.println(queryByName);
        if (null != queryByName) {
            Admin adminUpdate = new Admin(
                    queryByName.getAdminId(),
                    courierName,
                    password,
                    courierPhone,
                    queryByName.getCardId()
            );
            request.getSession().removeAttribute("adminName");
            request.getSession().setAttribute("adminName",courierName);
            Admin adminResult = adminService.updateAdmin(adminUpdate);
            ArrayList<Object> objects = new ArrayList<>();
            objects.add(adminResult);
            String toJson = JSONUtil.toJson(new Message(200, "修改成功", objects));
            System.out.println(toJson);
            return toJson;
        }
        String toJson = JSONUtil.toJson(new Message(400, "修改失败", null));
        System.out.println(toJson);
        return toJson;
    }


    @ResponseBody("/wx/courier/updateCourierPwd.do")
    public String updateCourierPwd(HttpServletRequest request, HttpServletResponse response){
        response.setCharacterEncoding("utf-8");
        String oldPassword = request.getParameter("oldPassword");
        String adminPassword = request.getParameter("newPassword");
        Integer code = Integer.valueOf(request.getParameter("code"));
        Integer code1 = (Integer) request.getSession().getAttribute("code");
        System.out.println(code);
        System.out.println(request.getSession().getAttribute("code"));
        System.out.println(!(String.valueOf(code).equals(String.valueOf(code1))));
        if (code == null || code1 == null
                || !(String.valueOf(code).equals(String.valueOf(code1)))) {
            Message msg = new Message(400, "快递员验证码失败", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        if (adminPassword == null) {
            Message msg = new Message(400, "快递员新密码为空", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        String adminName = (String) request.getSession().getAttribute("adminName");
        if (adminName == null) {
            Message msg = new Message(400, "快递员未登陆", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        Admin queryByAdmin = adminService.queryByName(adminName);
        if (!queryByAdmin.getAdminPwd().equals(oldPassword)) {
            Message msg = new Message(400, "快递员旧密码不正确！", null);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        queryByAdmin.setAdminPwd(adminPassword);
        Admin updateAdmin = adminService.updateAdmin(queryByAdmin);
        ArrayList<Object> objects = new ArrayList<>();
        objects.add(updateAdmin);
        if (updateAdmin != null && null != updateAdmin.getAdminId() && updateAdmin.getAdminPwd().equals(adminPassword)) {
            Message msg = new Message(200, "快递员密码修改成功", objects);
            String toJson = JSONUtil.toJson(msg);
            System.out.println(toJson);
            return toJson;
        }
        Message msg = new Message(400, "快递员密码更新失败", objects);
        String toJson = JSONUtil.toJson(msg);
        System.out.println(toJson);
        return toJson;
    }

}
